﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DXApplicationTangche.service;
using DXApplicationTangche.UC.款式管理.service;
using DXApplicationTangche.UC.面料库存.库存记录.service;
using DXApplicationTangche.UC.面料库存;
using DevExpress.XtraGrid.Demos.util;
using DXApplicationTangche.DTO;
using mendian;
using DXApplicationTangche.UC.样品管理.样品下单新.service;
using DXApplicationTangche.UC.款式异常;
using static DXApplicationTangche.UC.门店下单.form.Frm订单一览;
using DXApplicationTangche.UC.样品管理.样品下单新;
using System.Net;
using System.IO;
using DXApplicationTangche.report;
using DevExpress.XtraReports.UI;
using DXApplicationTangche.UC.订单一览新.订单预览新.service;
using DXApplicationTangche.UC.项目成果管理;
using DXApplicationTangche.UC.项目成果管理.service;
using DXApplicationTangche.UC.订单一览新.改版;
using DXApplicationTangche.UC.订单一览新.订单预览新.model;
using DXApplicationTangche.UC.订单一览新.订单预览新;
using DXApplicationTangche.UC.订单一览新.辅料.辅料下单;
using DXApplicationTangche.UC.订单一览新.辅料.service;
using DXApplicationTangche.UC.订单.service;
using DXApplicationTangche.UC.生产计划.编排生产批.service;
using DXApplicationTangche.Utils;
using DXApplicationTangche.UC.款式尺寸;
using System.Diagnostics;
using DXApplicationTangche.UC.款式管理;
using DXApplicationTangche.UC.门店下单.DTO;

namespace DXApplicationTangche.UC.样品管理.样品订单预览
{
    public partial class Form样品订单预览新 : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        #region 变量
        private String formId;
        private String batchNo;
        private Double batchQuantiry;
        private Boolean urgentFlg = false;
        //uc
        //private XtraUserControl辅料选择 uC辅料 = new XtraUserControl辅料选择();
        private 订单预览新Model model;
        public 款式图片一览Dto 款式基本信息 = new 款式图片一览Dto();
        #endregion
        /// <summary>
        /// 进入订单预览界面
        /// </summary>
        /// <param name="orderId"></param>
        public Form样品订单预览新(String orderId)
        {
            InitializeComponent();
            try
            {
                this.model = new 订单预览新Model(orderId, Enum订单查询.按照订单号查询订单);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.model.select尺寸();
            this.订单信息呈现();
            this.订单基本信息呈现();
            this.barButtonItem订单纸预览.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            this.barButtonItem编排生产计划.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
        }
        /// <summary>
        /// 改版进入预览页面
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="batchNo"></param>
        public Form样品订单预览新(String orderId, String batchNo)
        {
            InitializeComponent();
            this.batchNo = batchNo;
            try
            {
                this.model = new 订单预览新Model(orderId, Enum订单查询.按照订单号查询订单);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.model.select尺寸();
            this.订单信息呈现();
            this.订单基本信息呈现();
            this.barButtonItem订单纸预览.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            this.barButtonItem编排生产计划.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            this.barButtonItem改版完成.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
        }
        /// <summary>
        /// 生产批相关页面进入
        /// </summary>
        /// <param name="dTO生产批"></param>
        public Form样品订单预览新(DTO生产批 dTO生产批)
        {
            InitializeComponent();
            this.batchNo = dTO生产批.batchNo;
            this.batchQuantiry = dTO生产批.batchQuantiry;
            this.urgentFlg = dTO生产批.urgentFlg;
            try
            {
                this.model = new 订单预览新Model(dTO生产批.orderId, Enum订单查询.按照订单号查询订单);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.model.select尺寸();
            this.订单信息呈现();
            this.订单基本信息呈现();
        }
        private void 订单信息呈现()
        {
            //订单基本信息
            this.formId = this.model.OrderCommitDTO返回.fromId;
            this.textBox款名.Text = this.model.OrderCommitDTO返回.styleNameCn;
            this.pictureBox款式.LoadAsync(款式Service.get款式图(this.model.OrderCommitDTO返回.refStyleId));
            this.textBox面料.Text = this.model.OrderCommitDTO返回.materialCode + " " + this.model.OrderCommitDTO返回.materialNameCn;
            this.textBox成分.Text = this.model.OrderCommitDTO返回.composition;
            try { this.pictureBox面料.LoadAsync(面料记录Service.get面料图(this.model.OrderCommitDTO返回.materialCode)); } catch { }
            this.textBox幅宽.Text = this.model.OrderCommitDTO返回.width;
            //
            if (!String.IsNullOrWhiteSpace(this.model.OrderCommitDTO返回.styleSizeCd))
            {
                try { this.chicun01.Text = this.model.OrderCommitDTO返回.styleSizeCd.Replace("IGS_GROUP_SIZE-", "").Replace("EGS_GROUP_SIZE-", ""); } catch { }
            }
            this.treeList尺寸.DataSource = this.model.尺寸.measureItemDTOS;
            // 辅料uc
            //this.uC辅料 =
            //    new XtraUserControl辅料选择(
            //        new 标识StyleAccessoryDTO(false, this.model.OrderCommitDTO返回.styleAccessoryDTOs),
            //        this.model.OrderCommitDTO返回.materialCode
            //        );
            //this.uC辅料.Dock = DockStyle.Fill;
            //this.panel辅料.Controls.Clear();
            //this.panel辅料.Controls.Add(this.uC辅料);
            //样品备注文件
            this.gridControl备注文件.DataSource = 样品下单Service.get备注项目详情(this.formId);
            this.gridView备注文件.ExpandAllGroups();
        }

        private void 订单基本信息呈现()
        {
            if (!String.IsNullOrWhiteSpace(this.model.OrderCommitDTO返回.styleSizeCd))
            {
                try { this.chicun01.Text = this.model.OrderCommitDTO返回.styleSizeCd.Replace("IGS_GROUP_SIZE-", "").Replace("EGS_GROUP_SIZE-", ""); } catch { }
            }
            //
            this.textBox销售信息姓名.Text = this.model.OrderCommitDTO返回.customerName;
            this.textBox销售信息电话.Text = this.model.OrderCommitDTO返回.mobile;
        }

        private void 下载备注文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string fileName = FunctionHelper.GetgridViewValue(
                this.gridView备注文件,
                this.gridView备注文件.FocusedRowHandle,
                "fileName");
            string filePath = FunctionHelper.GetgridViewValue(
                this.gridView备注文件,
                this.gridView备注文件.FocusedRowHandle,
                "filePath");
            if (String.IsNullOrEmpty(fileName))
            {
                MessageBox.Show("暂无文件");
            }
            else
            {
                FolderBrowserDialog sFD = new FolderBrowserDialog();
                DialogResult rdr = sFD.ShowDialog();
                string selectFileName = sFD.SelectedPath;
                if (rdr == System.Windows.Forms.DialogResult.OK && !string.IsNullOrEmpty(selectFileName))
                {
                    try
                    {
                        //通过url下载文件
                        WebClient wClient = new WebClient();
                        wClient.Credentials = System.Net.CredentialCache.DefaultCredentials;
                        wClient.DownloadFile(URL.图片url + URL.样品文件路径 + filePath, selectFileName + "\\" + fileName);
                        MessageBox.Show("保存成功");
                    }
                    catch
                    {
                        MessageBox.Show("保存失败");
                    }
                }
            }
        }

        private void barButtonItem新增备注文件_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            new Form样品文件(this.formId).ShowDialog();
            this.gridControl备注文件.DataSource = 样品下单Service.get备注项目详情(formId);
            this.gridView备注文件.RefreshData();
            this.gridView备注文件.ExpandAllGroups();
        }

        private void 预览备注文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string fileName = FunctionHelper.GetgridViewValue(
                this.gridView备注文件,
                this.gridView备注文件.FocusedRowHandle,
                "fileName");
            string filePath = FunctionHelper.GetgridViewValue(
                this.gridView备注文件,
                this.gridView备注文件.FocusedRowHandle,
                "filePath");
            //下载文件到本地项目下指定文件
            FileUtil.DownloadPicture(URL.图片url + URL.样品文件路径 + filePath, @"doc\" + fileName, -1);
            string extension = Path.GetExtension(fileName);
            //文件后缀 带点（.）
            if (extension.Equals(".pdf"))
            {
                new Form备注文件预览PDF(@"doc\" + fileName).ShowDialog();
            }
            else if (extension.Equals(".doc") || extension.Equals(".docx"))
            {
                new Form备注文件预览DOC(@"doc\" + fileName).ShowDialog();
            }
        }

        private void barButtonItem订单纸预览_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            订单导出DTO 订单导出DTO =
                new 订单导出DTO(
                    this.model.OrderCommitDTO返回,
                    this.pictureBox款式.Image,
                    this.pictureBox面料.Image,
                    this.batchNo,
                    this.batchQuantiry,
                    this.urgentFlg
                    );
            List<订单导出DTO> 订单导出DTOs = new List<订单导出DTO>();
            订单导出DTOs.Add(订单导出DTO);
            XtraReport批次打印 report = new XtraReport批次打印();
            report.样品颜色水印();
            report.DataSource = 订单导出DTOs;
            ReportPrintTool tool = new ReportPrintTool(report);
            tool.ShowPreview();
        }

        private void barButtonItem编排生产计划_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            new Form项目成果提交(
                    new DTO项目成果提交(
                        this.batchNo,
                        "00.0001",
                        FunctionHelper.JsonSerialization(this.batchNo)
                        ),
                    true
                    ).ShowDialog();
        }

        private void barButtonItem改版完成_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            new Form改版完成(
                    this.batchNo
                    ).ShowDialog();
        }

        private void barButtonItem修改客户信息_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            new Form更改订单收货地址(this.model.OrderCommitDTO返回).ShowDialog();
        }
        private void treeList尺寸_CellValueChanged(object sender, DevExpress.XtraTreeList.CellValueChangedEventArgs e)
        {
            try
            {
                this.model.尺寸.build更改尺寸(
                        this.treeList尺寸.FocusedNode["id"].ToString(),
                        e.Column.FieldName,
                        e.Value.ToString(),
                        this.model.OrderCommitDTO返回.styleId,
                        this.model.OrderCommitDTO返回.orderId
                        );
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.treeList尺寸.DataSource = this.model.尺寸.measureItemDTOS;
            this.treeList尺寸.Refresh();
        }

        private void barButtonItem导入尺寸_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string styleCode = this.model.OrderCommitDTO返回.styleNameCn.Split()[0];
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            ExcelAndPath excelAndPath = ExcelUtil.getExcelDatasAndPath();
            if (excelAndPath == null)
            {
                return;
            }
            DataSet result = excelAndPath.DataSet;
            stopWatch.Stop();
            System.Diagnostics.Debug.WriteLine("导成Dataset用时" + stopWatch.ElapsedMilliseconds + "ms");
            stopWatch.Start();
            if (result == null)
            {
                return;
            }
            DataTable dataTable = result.Tables[0];
            List<DTO尺寸> list = new List<DTO尺寸>();
            String ITEM_CD;
            String ITEM_VALUE;
            String ITEM_NAME_CN;
            for (int i = 1; i < 100; i++)
            {
                try
                {
                    if (String.IsNullOrEmpty(dataTable.Rows[i]["Column0"].ToString()))
                    {
                        break;
                    }
                }
                catch (Exception)
                {
                    break;
                }
                ITEM_CD = dataTable.Rows[i]["Column0"].ToString();
                ITEM_VALUE = dataTable.Rows[i]["Column1"].ToString();
                ITEM_NAME_CN = dataTable.Rows[i]["Column2"].ToString();
                for (int j = 3; j < 100; j++)
                {
                    try
                    {
                        if (String.IsNullOrEmpty(dataTable.Rows[0]["Column" + j.ToString()].ToString()))
                        {
                            break;
                        }
                    }
                    catch (Exception)
                    {
                        break; ;
                    }
                    list.Add(new DTO尺寸(ITEM_CD, ITEM_VALUE, ITEM_NAME_CN, dataTable.Rows[i]["Column" + j.ToString()].ToString(), styleCode, "IGS_GROUP_SIZE-" + dataTable.Rows[0]["Column" + j.ToString()].ToString()));
                }
            }
            stopWatch.Stop();
            System.Diagnostics.Debug.WriteLine("导成List用时" + stopWatch.ElapsedMilliseconds + "ms");
            stopWatch.Start();
            new Frm尺寸导入预览(list, styleCode).ShowDialog();
            stopWatch.Stop();
            System.Diagnostics.Debug.WriteLine("Post用时" + stopWatch.ElapsedMilliseconds + "ms");
            this.刷新尺寸组();
        }

        private void 刷新尺寸组()
        {
            this.chicun01.Items.Clear();
            List<String> 尺码 = new List<string>();
            尺码 = FunctionHelper.JsonDeserialization<List<String>>(
                RestCall.httpGetMethod(
                    URL.接口url + "/size/findSizeCdByStyleNameCn?styleNameCn=" + this.model.OrderCommitDTO返回.styleNameCn.Split()[0]
                    ));
            foreach (String str in 尺码)
            {
                this.chicun01.Items.Add(str);
            }
        }
        private void chicun01_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.model.OrderCommitDTO返回.styleSizeCd = "IGS_GROUP_SIZE-" + this.chicun01.Text.Trim();
            this.model.尺寸 = FunctionHelper.JsonDeserialization<DTOStyleMeasureItems>(
                        RestCall.httpGetMethod(
                            URL.接口url + "/style/generateStyleMeasureItemsByStyleNameCn?SIZE_CD="
                                        + this.model.OrderCommitDTO返回.styleSizeCd
                                        + "&styleNameCn=" + this.model.OrderCommitDTO返回.styleNameCn.Split()[0]
                                        + "&categoryId=" + this.model.build查询款式类别().styleCategoryDTO.id
                                    )
                        );
            if(this.model.尺寸.measureItemDTOS.Count> 0)
            {
                //  更新订单尺寸相关数据
                订单预览新Service.updateOrderCommitSizeAndMeasureItems(
                    this.model.OrderCommitDTO返回.buildOrderCommit尺寸(this.model.尺寸)
                    );
            }
            this.treeList尺寸.DataSource = this.model.尺寸.measureItemDTOS;
            this.treeList尺寸.Refresh();
        }

        private void barButtonItem导入设计点_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                new Frm款式维护设计点导入(this.model.OrderCommitDTO返回.styleNameCn).ShowDialog();
            }
            catch { }
        }

        private void barButtonItem修改辅料完成_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //  调用更改辅料接口
            //this.model.saveAccessory(this.uC辅料.build().styleAccessoryDTOs);
            //MessageBox.Show("操作完成");
        }
    }
}